import 'package:flutter/material.dart';
import 'package:o_amap/aMapModule/common/latlng.dart';
import 'package:o_amap/aMapModule/location/amap_location.dart';
import 'package:o_amap/aMapModule/location/location_client_options.dart';
import 'package:o_amap/aMapModule/map/amap_controller.dart';
import 'package:o_amap/aMapModule/map/amap_view.dart';
import 'package:o_amap/aMapModule/map/model/marker_options.dart';
import 'package:o_amap/aMapModule/map/model/my_location_style.dart';
import 'package:o_amap/aMapModule/map/model/polyline_options.dart';
import 'package:o_amap/aMapModule/map/model/show_area_options.dart';
import 'package:o_amap/aMapModule/map/model/ui_settings.dart';
import 'package:o_amap/aMapModule/nav/amap_nav.dart';
import 'package:o_amap/aMapModule/nav/model/calculate_result.dart';
import 'package:o_amap/aMapModule/search/amap_search.dart';
import 'package:o_amap/aMapModule/search/model/Input_tips_result.dart';
import 'package:o_amap/aMapModule/search/model/geocode_result.dart';
import 'package:o_amap/aMapModule/search/model/poi_result.dart';
import 'package:o_amap/aMapModule/search/model/poi_search_query.dart';
import 'package:o_amap/aMapModule/search/model/regeocode_result.dart';
import 'package:o_amap_example/should_rebuild_widget.dart';

class MapTestPage extends StatefulWidget {
  @override
  _MapTestPageState createState() => _MapTestPageState();
}

class _MapTestPageState extends State<MapTestPage> {
  bool isShowMap = false;
  String _locationMsg = 'Unknown';
  AMapView _aMapView;
  String _method = '';
  AMapController _controller;

  @override
  void initState() {
    super.initState();
  }

  void initMapView() {
    _aMapView = AMapView(onAMapViewCreated: _aMapCallback);
    setState(() {});
  }

  Future<void> _aMapCallback(AMapController controller) async {
    if (_aMapView == null) {
      initMapView();
    } else {
      _controller = controller;
      _addStartAndEndMark(controller);
    }
  }

  void _addStartAndEndMark(AMapController controller) async {
    switch (_method) {
      case 'setMapType':
        controller?.setMapType(1);
        break;
      case 'setZoomLevel':
        controller?.setZoomLevel(5);
        break;
      case 'setPosition':
        controller?.setPosition(target: LatLng(22.817746, 108.36637));
        break;
      case 'changeLatLng':
        controller?.changeLatLng(LatLng(24.817746, 108.36637));
        break;
      case 'getCenterLatlng':
        LatLng result = await controller?.getCenterLatlng();
        _locationMsg = '中心点：' + result.toJson().toString();
        break;
      case 'showIndoorMap':
        controller?.showIndoorMap(true);
        break;
      case 'setUiSettings':
        controller?.setUiSettings(UiSettings());
        break;
      case 'setMyLocationStyle':
        controller?.setMyLocationStyle(MyLocationStyle(
            showMyLocation: true,
            myLocationIcon: 'images/end.png',
            radiusFillColor: Colors.red,
            strokeColor: Colors.blue,
            strokeWidth: 2));
        break;
      case 'addMarker':
        controller?.addMarker(MarkerOptions(
          position: LatLng(40.924936, 116.212184),
          anchorV: 0.5,
          icon: 'images/start.png',
          infoWindowEnable: false,
          extData: {'id': '0'},
        ));
        controller?.changeLatLng(LatLng(40.924936, 116.212184));
        break;
      case 'addMarkers':
        double freight = 10.0;
        CalculateResult result = await AMapNavi().calculateDriveRoute(
          startLat: 39.924936,
          startLon: 116.212184,
          endLat: 22.817746,
          endLon: 108.36637,
        );
        List<MarkerOptions> list = List<MarkerOptions>();
        MarkerOptions start = MarkerOptions(
          position: result?.result[0]?.startPoint,
          anchorV: 0.5,
          icon: 'images/start.png',
          infoWindowEnable: false,
          extData: {'id': '0'},
        );
        MarkerOptions end = MarkerOptions(
          position: result?.result[0]?.endPoint,
          icon: 'images/end.png',
          title: '  ￥${freight.toStringAsFixed(2)}',
          snippet:
              '${(result?.result[0]?.allLength / 1000).toStringAsFixed(2)}',
          anchorV: 0.5,
          extData: {
            'id': '1',
            'dic_time': '2',
            'infoWindowFlag': LSJ_DRIVER_ACCEPT_ORDER_FLAG
          },
        );
        list.add(start);
        list.add(end);
        controller?.addMarkers(list, moveToCenter: false);
        // 划线
        controller.addPolyline(PolylineOptions(
          latLngList: result?.result[0]?.coordList,
          width: 10.0,
          isUseTexture: true,
          isUseGradient: true,
          color: Colors.blue,
        ));
        // 显示安全区域
        List<LatLng> bounds = List<LatLng>();
        bounds.add(result?.result[0]?.startPoint);
        bounds.add(result?.result[0]?.endPoint);
        controller?.setShowArea(ShowAreaOptions(latLngList: bounds));
        break;
      case 'clearMarkers':
        controller?.clearMarkers();
        break;
      case 'clear':
        controller?.clear();
        break;
      case 'setPointToCenter':
        controller?.setPointToCenter(1, 1);
        break;
    }

    if (!mounted) return;
    if (_method != 'showIndoorMap') {
      Navigator.of(context).pop();
    }
    setState(() {});
  }

  void _showBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SingleChildScrollView(
            child: Column(
              children: [
                Divider(
                  height: 4,
                  color: Colors.blue,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Text(
                    "地图",
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.blue,
                    ),
                  ),
                ),
                Column(
                  children: [
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('创建地图'),
                          onTap: () {
                            isShowMap = true;
                            _method = '';
                            initMapView();
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('地图模式'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'setMapType';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('缩放等级'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'setZoomLevel';
                            _aMapCallback(_controller);
                          },
                        )
                      ],
                    ),
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          children: [
                            GestureDetector(
                              child: Text('地图中心点'),
                              onTap: () {
                                isShowMap = true;
                                _method = 'setPosition';
                                _aMapCallback(_controller);
                              },
                            ),
                            SizedBox(
                              width: 10,
                            ),
                            GestureDetector(
                              child: Text('移至某位置'),
                              onTap: () {
                                isShowMap = true;
                                _method = 'changeLatLng';
                                _aMapCallback(_controller);
                              },
                            ),
                            SizedBox(
                              width: 10,
                            ),
                            GestureDetector(
                              child: Text('中心点'),
                              onTap: () {
                                isShowMap = false;
                                _method = 'getCenterLatlng';
                                _aMapCallback(_controller);
                              },
                            )
                          ],
                        ),
                      ),
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('室内地图'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'showIndoorMap';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('地图初始化'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'setUiSettings';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('位置图标'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'setMyLocationStyle';
                            _aMapCallback(_controller);
                          },
                        )
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('添加mark'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'addMarker';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('添加marks和添加线'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'addMarkers';
                            _aMapCallback(_controller);
                          },
                        )
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('清除可视mark'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'clearMarkers';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('删除覆盖物'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'clear';
                            _aMapCallback(_controller);
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('地图中心点'),
                          onTap: () {
                            isShowMap = true;
                            _method = 'setPointToCenter';
                            _aMapCallback(_controller);
                          },
                        )
                      ],
                    )
                  ],
                ),
                Divider(
                  height: 4,
                  color: Colors.blue,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Text(
                    "定位",
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.blue,
                    ),
                  ),
                ),
                Column(
                  children: [
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('开始定位'),
                          onTap: () async {
                            LocationClientOptions options =
                                LocationClientOptions(
                              isOnceLocation: true,
                              interval: 10000,
                              distanceFilter: 200,
                            );
                            AMapLocation().startLocation(options).listen(
                              (event) {
                                if (!mounted) return;
                                setState(() {
                                  isShowMap = false;
                                  _locationMsg = '定位信息：' + event.toString();
                                });
                              },
                            );
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('停止定位'),
                          onTap: () async {
                            AMapLocation().stopLocation();
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg = '定位信息：' + '停止定位';
                            });
                          },
                        )
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('销毁定位'),
                          onTap: () async {
                            AMapLocation().destroyLocation();
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg = '定位信息：' + '销毁定位';
                            });
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('两点距离'),
                          onTap: () async {
                            num result =
                                await AMapLocation().calculateLineDistance(
                              LatLng(39.924936, 116.212184),
                              LatLng(22.817746, 108.36637),
                            );
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg = '两点距离：' + result.toString();
                            });
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('转换'),
                          onTap: () async {
                            LatLng result =
                                await AMapLocation().coordinateTransformation(
                              1,
                              LatLng(39.924936, 116.212184),
                            );
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg = '转换：' + result.toString();
                            });
                          },
                        )
                      ],
                    )
                  ],
                ),
                Divider(
                  height: 4,
                  color: Colors.blue,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Text(
                    "导航",
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.blue,
                    ),
                  ),
                ),
                Row(
                  children: [
                    GestureDetector(
                      child: Text('规划路线'),
                      onTap: () async {
                        // 规划路线
                        CalculateResult result =
                            await AMapNavi().calculateDriveRoute(
                          startLat: 39.924936,
                          startLon: 116.212184,
                          endLat: 22.817746,
                          endLon: 108.36637,
                        );
                        if (!mounted) return;
                        setState(() {
                          _locationMsg = '规划路线结果：' + result.toJson().toString();
                        });
                      },
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    GestureDetector(
                      child: Text('开始导航'),
                      onTap: () async {
                        // 开始导航
                        AMapNavi().startNav(
                          endLat: 39.924936,
                          endLon: 116.212184,
                          name: '北京',
                        );
                        if (!mounted) return;
                        setState(() {
                          _locationMsg = '开始导航：' + '导航';
                        });
                      },
                    )
                  ],
                ),
                Divider(
                  height: 4,
                  color: Colors.blue,
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: Text(
                    "搜索",
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.blue,
                    ),
                  ),
                ),
                Column(
                  children: [
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('关键字搜索'),
                          onTap: () async {
                            // 搜索poi
                            PoiSearchQuery query = PoiSearchQuery(
                              query: '电影院',
                              city: '西安',
                              distanceSort: true,
                            );
                            PoiResult result =
                                await AMapSearch().searchPoi(query);
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg =
                                  '关键字搜索结果：' + result.toJson().toString();
                            });
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('周边搜索'),
                          onTap: () async {
                            // 周边搜索
                            PoiSearchQuery query = PoiSearchQuery(
                              query: '加油站',
                              building: '加油站',
                              location: LatLng(39.990459, 116.481476),
                              distanceSort: true,
                            );
                            PoiResult result =
                                await AMapSearch().searchPoiBound(query);
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg =
                                  '周边搜索结果：' + result.toJson().toString();
                            });
                          },
                        )
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Text('搜索输入'),
                          onTap: () async {
                            // 搜索输入
                            InputTipsResult result =
                                await AMapSearch().inputTips('故宫', city: '北京');
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg =
                                  '搜索输入结果：' + result.toJson().toString();
                            });
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('地址转坐标'),
                          onTap: () async {
                            // 逆地理编码
                            GeocodeResult result = await AMapSearch()
                                .searchGeocode(name: '天安门', city: '110000');
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg =
                                  '地址转坐标搜索结果：' + result.toJson().toString();
                            });
                          },
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        GestureDetector(
                          child: Text('逆地理编码'),
                          onTap: () async {
                            // 地址转坐标
                            LatLng point = LatLng(39.924936, 116.212184);
                            ReGeocodeResult result =
                                await AMapSearch().searchReGeocode(point);
                            if (!mounted) return;
                            setState(() {
                              isShowMap = false;
                              _locationMsg =
                                  '逆地理编码搜索结果：' + result.toJson().toString();
                            });
                          },
                        )
                      ],
                    )
                  ],
                ),
                SizedBox(
                  height: 100,
                )
              ],
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Container(
      height: double.infinity,
      width: double.infinity,
      child: Stack(
        children: [
          isShowMap
              ? Container(
                  width: size.width,
                  child: ShouldRebuild<AMapView>(
                    shouldRebuild: (oldWidget, newWidget) =>
                        oldWidget.aMapOptions != newWidget.aMapOptions,
                    child: _aMapView,
                  ),
                )
              : Text(_locationMsg),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: GestureDetector(
              onTap: _showBottomSheet,
              child: Container(
                height: 60,
                color: Colors.blue,
                alignment: Alignment.center,
                child: Text(
                  "地图功能菜单",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
